package eu.webhib.webblog.application;

import eu.webhib.frmwrk.persistence.PersistenceMngr;
import eu.webhib.frmwrk.utils.*;
import eu.webhib.webblog.domain.*;
import eu.webhib.webblog.service.factory.ServiceFactory;
import eu.webhib.webblog.service.intf.UserService;
import org.apache.log4j.Logger;

/**
 * Global application level tasks
 */
public class Application {

   private static final Logger log = Logger.getLogger(Application.class);
   private static final String PROPTERTIES_FILE_NAME = "webhib.properties";
   private static final String PERSISTENCE_UNIT_KEY = "database.persistence-unit";
   private static final String PERSISTENCE_UNIT_DEFAULT = "hsqldb";

   private Application() {
   }

   // called at application startup
   public static void startup() {
      log.info("startup");

      /** load properties from properties file(s) */
      ExtendedProperties prop = loadApplProperties();
      /** deliver properties to mailing system */
      MailUtils.setProperties(prop);
      /** initialize database */
      PersistenceMngr.createEntityManagerFactory(getPersistenceUnitName(), prop);

      /* populate database with default entries if emtpy */
      if (ServiceFactory.getUserService().count() > 0) {
         log.info("database already populated");
      } else {
         populateDatabase();
      }
   }

   public static String getPersistenceUnitName() {
      return ApplProperties.getProperties().getProperty(PERSISTENCE_UNIT_KEY, PERSISTENCE_UNIT_DEFAULT);
   }

   public static ExtendedProperties loadApplProperties() {
      /** load properties file(s) */
      String currentDir = System.getProperty("user.dir");
      String userHome = System.getProperty("user.home");
      String[] dirs = new String[3];
      dirs[0] = (currentDir != null ? currentDir + Consts.FILE_SEPARATOR : "") + ".." + Consts.FILE_SEPARATOR + "conf";
      dirs[1] = currentDir != null ? currentDir : ".";
      dirs[2] = userHome;
      ExtendedProperties prop = ApplProperties.loadProperties(PROPTERTIES_FILE_NAME, dirs);
      if (prop == null) {
         log.fatal("No properties file found !!!");
      }
      return prop;
   }

   public static void populateDatabase() {
      log.info("populateDatabase");
      UserService userService = ServiceFactory.getUserService();
      User user = userService.createNew();
      user.setRegistered("Administrator", "", "admin", "admin");
      user.setRegisterConfirmed();
      user.setUserRole(UserRole.getAdminRole());
      userService.save(user);
      PersistenceMngr.commitTransaction();
   }

   public static void resetDatabase() {
      log.info("resetDatabase");
      ServiceFactory.getUserService().deleteAll();
      PersistenceMngr.commitTransaction();
      populateDatabase();
   }
}
